package com.zhongxi.guoyuan.view.beautifulStore;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRouteGuideManager;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulStore.ShopInfoResult;
import com.zhongxi.guoyuan.entity.rewardcoin.ShopInfo;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StoreDetailActivity extends BaseActivity {


    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.viewflow)
    ViewFlow viewflow;
    @Bind(R.id.viewflowdic)
    CircleIndicator viewflowdic;
    @Bind(R.id.flow)
    FrameLayout flow;
    @Bind(R.id.tvStoreName)
    TextView tvStoreName;
    @Bind(R.id.rb)
    RatingBar rb;
    @Bind(R.id.tvWorkTime)
    TextView tvWorkTime;
    @Bind(R.id.tvPhone)
    TextView tvPhone;
    @Bind(R.id.tv_makeCall)
    TextView tvMakeCall;
    @Bind(R.id.tvPosition)
    TextView tvPosition;
    @Bind(R.id.ivMapNavi)
    TextView ivMapNavi;
    @Bind(R.id.tvRailWay)
    TextView tvRailWay;
    @Bind(R.id.tvBus)
    TextView tvBus;


    private BannerAdapter mBannerAdapter;
    private String shopid;
    private ShopInfo data;

    private static final String APP_FOLDER_NAME = "Meirongyuan";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private String mSDCardPath = null;
    public static List<Activity> activityList = new LinkedList<Activity>();

    private final static String authBaseArr[] =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};

    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private int authComRequestCode = 2;
    private final static int authBaseRequestCode = 1;
    private boolean hasRequestComAuth = false;

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };
    private ProgressDialog dialog;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_store_detail);
        ButterKnife.bind(this);
        tvTitle.setText("美容院详情");
        shopid = getIntent().getStringExtra("shopid");   //店铺号
        ImageUtils.setHeight(this, Constants.flowRate, flow);
    }

    /**
     * 左右轮播
     *
     * @param images
     */
    private void initViewFlow(List<String> images) {
        /**
         * 轮播
         */
        viewflow.setFlowIndicator(viewflowdic);

        if (images.size() > 0) {
            viewflow.setSideBuffer(images.size()); // 实际图片数量
        } else {
            viewflow.setSideBuffer(1);
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new BannerAdapter(context, images);
        } else {
            mBannerAdapter.replaceAll(images);
        }
        viewflow.setAdapter(mBannerAdapter);
        viewflow.startAutoFlowTimer();
    }

    @Override
    protected void initData() {
        super.initData();
        String str = "&shopid=" + shopid;
        getServer(Url.SHOP_INFO, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.INTERNET, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 100);
        } else {
            mapNavi();//初始化百度导航
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == authBaseRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                } else {
//                    Toast.makeText(StoreDetailActivity.this, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            initNavi();
        } else if (requestCode == authComRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                }
            }
            routeplanToNavi(mCoordinateType);
        } else if (requestCode == 100) {
            mapNavi();//初始化百度导航
        }
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            ShopInfoResult result = gson.fromJson(response, ShopInfoResult.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (null != result.getData() && !"".equals(result.getData())) {
                data = result.getData();
                initInfo(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (result.getCode() == 1000) {
                showShortToast("广告已失效");
                finish();
            }
            if (result.getCode() == 1032) {
                showShortToast("此类项目限次24次/年，已预约满，不可再预约，请选择其他项目！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化店铺信息
     *
     * @param info
     */
    private void initInfo(ShopInfo info) {
        try {
            if (null != info.getName() && !"".equals(info.getName())) {
                tvStoreName.setText(info.getName());
            } else {
                tvStoreName.setText("");
            }
            if (null != info.getWorkertime() && !"".equals(info.getWorkertime())) {
                tvWorkTime.setText(info.getWorkertime() + "  营业中");
            } else {
                tvWorkTime.setText("");
            }
            rb.setIsIndicator(true);
            if (null != info.getStarlevel() && !"".equals(info.getStarlevel())) {
                rb.setRating(Float.parseFloat(info.getStarlevel()));
            } else {
                rb.setRating(1.5f);
            }
            initViewFlow(info.getImages());
            if (null != info.getTel() && !"".equals(info.getTel())) {
                tvPhone.setText(info.getTel());
            } else {
                tvPhone.setText("");
            }
            if (null != info.getAddress() && !"".equals(info.getAddress())) {
                tvPosition.setText(info.getAddress());
            } else {
                tvPosition.setText("");
            }
            if (null != info.getTraffic() && !"".equals(info.getTraffic())) {
                tvRailWay.setText(info.getTraffic());
                tvBus.setText(info.getTraffic());
            } else {
                tvRailWay.setText("");
                tvBus.setText("");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.ivBack, R.id.tv_makeCall, R.id.ivMapNavi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tv_makeCall:
                if (null != data.getTel() && !"".equals(data.getTel())) {
                    String mphone = data.getTel();
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + mphone);
                    intent.setData(data);
                    startActivity(intent);
                } else {
                    showShortToast("电话号为空");
                }
                break;
            case R.id.ivMapNavi:
                if (data.getLongitude() != null && data.getDimensions() != null) {
                    if (dialog == null) {
                        dialog = new ProgressDialog(this);
                    }
                    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //样式为圆形
                    dialog.setCancelable(false);
                    dialog.setOnKeyListener(keyListener);
                    dialog.setMessage("正在获取数据,请稍后...");
                    dialog.show();
                    if (BaiduNaviManager.isNaviInited()) {
                        routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                    } else {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                } else {
                    ToastUtil.show(getString(R.string.loseDataOfBaiduNavi));
                }
                break;
        }
    }

    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == keyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
            return false;
        }
    };


    private void mapNavi() {
        activityList.add(this);
        // 打开log开关
        BNOuterLogUtil.setLogSwitcher(true);
        if (initDirs()) {
            initNavi();
        }
    }

    /**
     * 获取目录
     *
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private boolean hasBasePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {

                requestPermissions(authBaseArr, authBaseRequestCode);
                return;

            }
        }

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        }, null, ttsHandler, ttsPlayStateListener);

    }

    private void initSetting() {
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);

        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, Constants.BAIDUMAP_ID);
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    private boolean hasCompletePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private BNRoutePlanNode.CoordinateType mCoordinateType = null;

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        mCoordinateType = coType;
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    requestPermissions(authComArr, authComRequestCode);
                    return;
                }
            }

        }
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "我的位置", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(data.getLongitude()), Double.parseDouble(data.getDimensions()), data.getName(), null, coType);
                break;
            }
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            /*
             * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "4");
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        BNRouteGuideManager.getInstance().forceQuitNaviWithoutDialog();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        } else {
            super.onBackPressed();
        }
    }
}
